from minio import Minio
from minio.error import S3Error
import logging

from project.settings import os, BASE_DIR, baseImgUrl, MINIO_URL, MINIO_access_key, MINIO_secret_key

# 使用endpoint、access key和secret key来初始化minioClient对象。
minioClient = Minio(MINIO_URL, access_key=MINIO_access_key, secret_key=MINIO_secret_key, secure=False)

def saveFile(fp, save_path):
    if fp.multiple_chunks(): # 判断上传文件大于2.5MB的大文件
        # 为真
        file_yield = fp.chunks() # 迭代写入文件
        with open(save_path,'wb') as f:
            for buf in file_yield: # for情况执行无误才执行 else
                f.write(buf)
        print("大文件写入完毕")
    else:
        with open(save_path,'wb') as f:
            # print('小文件写入', fp.read())
            f.write(fp.read())
        print("小文件写入完毕")
        
def uploadFile(fp, bucket, filePath, fileName):
    save_path = os.path.join(BASE_DIR, 'static/') + fileName
    print('save_path', save_path)
    if fp:
        saveFile(fp, save_path)

    if minioClient.bucket_exists(bucket_name=bucket):  # bucket_exists：检查桶是否存在
        print("该存储桶已经存在")
    else:
        print("该存储桶不存在", bucket)
        minioClient.make_bucket(bucket)
    try:
        logging.info("start upload file")
        minioClient.fput_object(bucket, filePath + '/' + fileName, save_path) #fput_object函数上传文件，参数2为minio地址，参数3为本地地址。
        logging.info(fileName + ", is successfully uploaded")
    except FileNotFoundError as err:
        logging.error('upload_failed: '+ str(err))
    except S3Error as err:
        logging.error("upload_failed:", err)
    print('fileName=', fileName , 'save_path=', save_path)
    return bucket + '/' + filePath + '/' + fileName

